<template>
	<view class="AIgenerate" :style="'background-Image: url('+ homebgc +');'">
		<view class="top"></view>
		<view class="left" @click="NavLeft"><text class="tn-icon-left"
				style="font-size: 35rpx;font-weight: bold;"></text></view>
		<view class="title">动作分析报告</view>
		<view v-if="!analysis" class="analysis">
			<image :src=" websiteUrl + photoPath" mode="heightFix" style="width: 100%;height: 400rpx;" class="pic">
			</image>
		</view>
		<view v-else class="videos">
			<video id="myVideo" :src=" websiteUrl + videoPath" :vslide-gesture="true"
				@fullscreenchange="fullscreenchange" style="width: 100%;height: 400rpx;border-radius: 32rpx"
				enable-danmu danmu-btn controls></video>
		</view>
		<scroll-view :enable-back-to-top="true" :enable-flex="true" id="scrollview" scroll-y="true"
			:scroll-top="scrollTop" class="scroll-view">
			<view ref="ChatBoxRef" id="msglistview" class="body">
				<view class="content">
					<div class="loading" v-if="dialogue == ''">
						<tn-loading color="#AAAAAA"></tn-loading>
						<div class="loadcontent">舞界AI正在为您生成回答···</div>
					</div>
					<view class="container" v-else>
						<wemark :md="dialogue" link highlight type="wemark"></wemark>
						<button v-if="generateFlag" class="generate" @click="ShareMoments"><span>生成报告</span></button>
					</view>
				</view>
			</view>
		</scroll-view>
		<tn-modal v-model="show" :radius="24" :custom="true" :button="button" :maskCloseable="false"
			:showCloseBtn="false">
			<view class="model-Box">
				<view class="title">{{title}}</view>
				<view class="content">{{content}}</view>
				<view class="model-Btn">
					<button @click="ErrorBtn">确认</button>
				</view>
			</view>
		</tn-modal>
	</view>
</template>

<script>
	import {
		connectSocket,
		sendSocketMessage,
		getSocketMessage,
		closeSocketAI
	} from "@/common/Socket.js"
	export default {
		data() {
			return {
				homebgc: this.$websiteUrl + 'static/web_files/Home_bj.svg',
				websiteUrl: this.$websiteUrl,
				webSocket: this.$webSocket,
				scrollTop: 0,
				photoPath: '',
				videoPath: "",
				vsphoto: '',
				dataQueue: [],
				dataRendered: false,
				dialogue: '',
				dataStr: '',
				photos: {},
				videos: {},
				photosType: '',
				generateFlag: false,
				analysis: false,
				show: false,
				title: '警告',
				content: '',
				button: [{
					text: '重新上传',
					backgroundColor: '#7265E3',
					fontColor: '#FFFFFF'
				}, ],
			}
		},
		onLoad(options) {
			connectSocket(this.webSocket + `ws/call_model/`)
			this.generateFlag = false
			if (options.photo) {
				this.analysis = false
				const photo = JSON.parse(decodeURIComponent(options.photo))
				if (photo.photoPath) {
					this.photos = photo
					this.init(photo, 'image')
				}
			} else {
				this.analysis = true
				const video = JSON.parse(decodeURIComponent(options.video))
				if (video.videoPath) {
					this.videos = video
					this.init(video, 'video')
				}
			}
		},
		onUnload() {
			// 页面卸载时执行的操作
			console.log('页面被卸载');
			closeSocketAI()
		},
		methods: {
			ErrorBtn() {
				const data = {
					index: 1
				}
				const objStr = encodeURIComponent(JSON.stringify(data))
				wx.reLaunch({
					url: `/pages/index/index?userInfo=${objStr}`
				})
				this.show = false
			},
			fullscreenchange() {
				// 获取 videoContext 对象
				const videoContext = wx.createVideoContext('myVideo', this);
				// 请求全屏模式
				videoContext.requestFullScreen({
					direction: 90
				});
			},
			NavLeft() {
				if (!this.analysis) {
					if (this.photosType) {
						const data = {
							index: 1
						}
						const objStr = encodeURIComponent(JSON.stringify(data))
						wx.reLaunch({
							url: `/pages/index/index?userInfo=${objStr}`
						})

					} else {
						const objStr = encodeURIComponent(JSON.stringify(this.photos))
						wx.reLaunch({
							url: `/basicPage/photograph/index?photo=${objStr}`
						})
					}
				} else {
					const data = {
						index: 2
					}
					const objStr = encodeURIComponent(JSON.stringify(data))
					wx.reLaunch({
						url: `/pages/index/index?userInfo=${objStr}`
					})
				}
			},
			ShareMoments() {
				if (!this.analysis) {
					const data = {
						dialogue: this.dialogue,
						photoPath: this.websiteUrl + this.photoPath,
					}
					const objStr = encodeURIComponent(JSON.stringify(data))
					wx.reLaunch({
						url: `/basicPage/Reporting/index?photo=${objStr}`
					})
				} else {
					const data = {
						dialogue: this.dialogue,
						videoPath: this.websiteUrl + this.videoPath
					}
					const objStr = encodeURIComponent(JSON.stringify(data))
					wx.reLaunch({
						url: `/basicPage/Reporting/index?video=${objStr}`
					})
				}
			},
			async init(photo, str) {
				
				await getSocketMessage(this.handleMessages)
				if (str == "image") {
					this.photoPath = photo.photoPath;
					this.vsphoto = photo.dance_action_image_url;
					if (photo.type) {
						this.photosType = photo.type
					}
					// 延迟函数替代 setTimeout
					await this.delay(300)
					const querydata = {
						analysis_type: 1,
						dance_action_name: photo.dance_action,
						user_id: uni.getStorageSync('userInfo').id,
						user_file_url: this.websiteUrl + photo.photoPath,
						dance_action_file_url: photo.dance_action_image_url
					}
					await sendSocketMessage(querydata)
				} else {
					setTimeout(() => {
						this.videoPath = photo.videoPath;
					}, 100)
					// 延迟函数替代 setTimeout
					await this.delay(300)
					const querydata = {
						analysis_type: 2,
						user_id: uni.getStorageSync('userInfo').id,
						user_file_url: this.websiteUrl + photo.videoPath,
					}
					await sendSocketMessage(querydata)
				}
			},
			// 延迟函数
			delay(ms) {
				return new Promise(resolve => setTimeout(resolve, ms))
			},

			// px转换成rpx
			rpxTopx(px) {
				let deviceWidth = wx.getSystemInfoSync().windowWidth
				let rpx = (750 / deviceWidth) * Number(px)
				return Math.floor(rpx)
			},

			// 滚动至聊天底部
			scrollToBottom(e) {
				setTimeout(() => {
					let query = uni.createSelectorQuery().in(this);
					query.select('#scrollview').boundingClientRect();
					query.select('#msglistview').boundingClientRect();
					query.exec((res) => {
						if (res[1].height > res[0].height) {
							this.scrollTop = this.rpxTopx(res[1].height - res[0].height)
						}
					})
				}, 15)

			},

			handleMessages(event) {
				if (event) {
					this.dataQueue.push(event);
					if (!this.dataRendered) {
						this.processNextMessage();
					}
				}
			},

			// 处理队列中的下一条消息
			async processNextMessage() {
				if (this.dataRendered) return
				this.dataRendered = true;
				while (this.dataQueue.length > 0) {
					const message = this.dataQueue.shift();
					await this.processData(message);
				}
				this.dataRendered = false;
				this.dataQueue = []
			},

			// 处理数据的函数，根据业务需求进行处理
			async processData(message) {
				if (message.complete) {
					if (message.text !== '') {
						this.content = message.text
						this.show = true
						this.generateFlag = false
						closeSocketAI()
						this.$store.dispatch('fetchUserInfo');
					} else {
						if (message.msg) {
							this.generateFlag = false
							closeSocketAI()
							this.$store.dispatch('fetchUserInfo');
						} else {
							this.generateFlag = true
							closeSocketAI()
							this.$nextTick(() => {
								this.scrollToBottom();
							});
							this.$store.dispatch('fetchUserInfo');
						}
					}

				} else {
					const charDelay = 0;
					this.dataStr += message.text;
					this.$set(this, 'dialogue', this.dataStr);
					this.scrollToBottom();
					await new Promise((resolve) => setTimeout(resolve, charDelay));
				}

			},
		}
	}
</script>

<style lang="scss" scoped>
	.AIgenerate {
		position: relative;
		padding-top: 70rpx;
		height: 100vh;
		overflow: hidden;
		background-size: cover;
		background-position: center center;
		background-repeat: no-repeat;
		padding: 0 48rpx;

		.top {
			height: 88rpx;
		}

		.left {
			display: flex;
			align-items: center;
			height: 88rpx;
			margin-left: -30rpx;
		}

		.title {
			font-weight: 500;
			font-size: 64rpx;
			color: #2D3142;
			line-height: 90rpx;
			text-align: left;
			font-style: normal;
			margin-bottom: 18rpx;
		}

		.analysis {
			display: flex;
			justify-content: center;
			align-items: center;
			padding: 20rpx 0rpx 24rpx 0rpx;

			.pic {
				border-radius: 28rpx;
				border: 2rpx solid #FFFFFF;
			}
		}

		.videos {
			height: 400rpx;
			margin-top: 54rpx;
		}

		.scroll-view {
			height: calc(100vh - 800rpx);

			.body {
				.content {
					margin-top: 20rpx;

					.loading {
						display: flex;
						align-items: center;

						.loadcontent {
							margin-left: 15rpx;
						}
					}
				}
			}

			.generate {
				margin-top: 48rpx;
				display: flex;
				justify-content: center;
				align-items: center;
				height: 104rpx;
				background: #7265E3;
				border-radius: 28rpx;
				color: #fff;
				font-weight: 500;
				font-size: 32rpx;

				span {
					margin-left: 15rpx;
				}
			}
		}

	}

	.model-Box {
		text-align: center;

		.title {
			margin: 0;
			text-align: center;
			font-size: 40rpx;
		}

		.content {
			font-size: 30rpx;
			color: #999;
			margin-bottom: 40rpx;
		}

		.model-Btn {
			button {
				background-color: #7265E3;
				border-radius: 50rpx;
				color: #fff;
			}
		}

	}
</style>